/*
 * Copyright 2019-2020 Mamoe Technologies and contributors.
 *
 * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
 * Use of this source code is governed by the GNU AFFERO GENERAL PUBLIC LICENSE version 3 license that can be found through the following link.
 *
 * https://github.com/mamoe/mirai/blob/master/LICENSE
 */

package net.mamoe.mirai.console.intellij.diagnostics.fix

import com.intellij.codeInspection.LocalQuickFix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.rootManager
import com.intellij.psi.PsiFile
import com.intellij.testFramework.writeChild
import org.jetbrains.kotlin.idea.inspections.KotlinUniversalQuickFix
import org.jetbrains.kotlin.idea.quickfix.KotlinCrossLanguageQuickFixAction
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.module
import org.jetbrains.kotlin.psi.KtClassOrObject


class ConfigurePluginMainServiceFix(
    element: KtClassOrObject,
) : KotlinCrossLanguageQuickFixAction<KtClassOrObject>(element), KotlinUniversalQuickFix, LocalQuickFix {

    override fun getFamilyName(): String = "Mirai Console"
    override fun getText(): String = "配置插件主类服务"

    override fun invokeImpl(project: Project, editor: Editor?, file: PsiFile) {
        val elementFqName = element?.fqName ?: return
        val sourceRoots = file.module?.rootManager?.sourceRoots ?: return

        val sourceRoot = sourceRoots.find { it.name.endsWith("resources") }
            ?: sourceRoots.find { it.name.contains("resources") }
            ?: sourceRoots.last()

        project.executeWriteCommand(name) {
            sourceRoot.writeChild("META-INF/services/net.mamoe.mirai.console.plugin.jvm.JvmPlugin", elementFqName.asString().toByteArray())
        }
    }
}
